import React, { useEffect, useState } from 'react'
import { useQuery } from 'remax'
import { Image, Text, View } from 'remax/one'
import { scanCode, showToast } from 'remax/wechat'
import RecycleView from 'remax-recycle-view/lib'
import { Button, Icon, Row, Space, Tag } from 'annar'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { requestCloud } from '@/hooks/use-cloud'
import Login from '@/components/login'
import styles from './index.css'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const OrderItem = ({ promotionCast: { promotion }, cost, createAt }: any) => {
  return (
    <View className={styles.itemArea}>
      <View className={styles.itemBox} hoverClassName="hover">
        <Row className={styles.fullHeight} align="middle">
          <View className={styles.itemBoxLeft}>
            <Image
              className={styles.avatarImg}
              src={promotion.imgUrls[0]}
              mode="aspectFill"
            />
          </View>
          <Space className={styles.itemBoxRight} direction="vertical" size={12}>
            <Row justify="space-between" align="middle">
              <View className="large-text ellipsis">{promotion.name}</View>
              <Tag color="green">电子券有效</Tag>
            </Row>
            <View className="small-text ellipsis">{promotion.description}</View>
            <Row justify="space-between" align="bottom">
              <Space align="center" size={12}>
                <Text className={styles.alarmText}>￥{cost}</Text>
                <Text className={styles.deletedText}>
                  ￥{promotion.originalPrice}
                </Text>
                <Tag color="red">
                  {Math.round((cost / promotion.originalPrice) * 100) / 10} 折
                </Tag>
              </Space>
              <Text className="small-text">{dayjs(createAt).fromNow()}</Text>
            </Row>
          </Space>
        </Row>
      </View>
    </View>
  )
}

export default () => {
  const [data, setData] = useState<any>([])
  const { q } = useQuery()
  useEffect(() => {
    checkin(decodeURIComponent(q))
  }, [])

  const checkin = async (code: string) => {
    try {
      const arr = code.match(/\/business\/ticket\/(.*)$/)
      const orderId = arr ? arr[1] : code
      const order = await requestCloud('checkin', { orderId })
      showToast({ title: '验证成功', duration: 3000, mask: true })
      setData([order].concat(data))
    } catch ({ errMsg }) {
      let content
      if (/scanCode:fail cancel/.test(errMsg)) {
        return
      } else if (/invalid qrcode/.test(errMsg)) {
        content = '二维码不合法'
      } else if (/different provider/.test(errMsg)) {
        content = '电子券不属于本店'
      } else if (/incorrect status/.test(errMsg)) {
        content = '电子券已经使用过'
      } else if (/order expired/.test(errMsg)) {
        content = '电子券已过期'
      } else {
        content = '网络错误'
      }
      wx.showModal({
        title: '验证失败',
        content,
        confirmText: '继续',
        cancelText: '返回',
        success: async res => {
          if (res.confirm) {
            const { result } = await scanCode()
            checkin(result)
          }
        },
      })
    }
  }

  return (
    <Login>
      <View className={styles.scanArea}>
        <Button
          className={styles.scanButton}
          type="primary"
          onTap={async () => {
            const { result } = await scanCode()
            checkin(result)
          }}
        >
          <Icon type="scan" color="#fff" size="70" />
        </Button>
      </View>
      {data &&
        (data.length ? (
          <RecycleView
            className={styles.mainArea}
            data={data.map((v: any) => ({ ...v, height: 220 }))}
            renderItem={(item, index) => {
              return <OrderItem {...item} />
            }}
          />
        ) : (
          <View className="empty-view small-text">
            请扫描客户出示的签到二维码
          </View>
        ))}
    </Login>
  )
}
